﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace OpenWaves.Video
{
    public interface IVideo
    {
        IEnumerable<IVideoThumbnail> Thumbnails { get; }
        string Title { get; }
        string Id { get; }
    }

    public static class VideoExtensions
    {
        public static IVideoThumbnail GetThumbnailForSize(this IVideo video, int width, int height)
        {
            var thumbnails = video.Thumbnails.OrderBy(thumbnail => thumbnail.Width).ToArray();
            var selectedThumbnailIndex = 0;
            for (var i = 0; i < thumbnails.Length - 1; i += 1)
            {
                var thumbnail = thumbnails[i];
                var nextThumbnail = thumbnails[i + 1];

                var tWidth = thumbnail.Width - width;
                var nWidth = nextThumbnail.Width - width;
                var sWidth = thumbnails[selectedThumbnailIndex].Width - width;

                var tWidthAbs = Math.Abs(tWidth);
                var nWidthAbs = Math.Abs(nWidth);
                var sWidthAbs = Math.Abs(sWidth);

                if (tWidthAbs <= nWidthAbs)
                {
                    if (tWidthAbs <= sWidthAbs && tWidth > 0)
                    {
                        selectedThumbnailIndex = i;
                    }
                    else if(tWidthAbs <= sWidthAbs && nWidth > 0)
                    {
                        selectedThumbnailIndex = i + 1;
                    }
                }
                else
                {
                    if (nWidthAbs <= sWidthAbs && nWidth > 0)
                    {
                        selectedThumbnailIndex = i + 1;
                    }
                }
            }
            return thumbnails[selectedThumbnailIndex];
        }
    }   
}
